package io.github.talelin.latticy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.github.talelin.latticy.dto.zty.ShopListDTO;
import io.github.talelin.latticy.dto.zty.child.ShopListDetailDTO;
import io.github.talelin.latticy.mapper.*;
import io.github.talelin.latticy.model.UserDO;
import io.github.talelin.latticy.pojo.*;
import io.github.talelin.latticy.service.SaleListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZTY
 * @since 2021-04-15
 */
@Service
@Transactional
public class SaleListServiceImpl extends ServiceImpl<SaleListMapper, SaleList> implements SaleListService {

    @Autowired
    SaleDetailMapper saleDetailMapper;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    SaleListMapper saleListMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    ShopStockMapper shopStockMapper;

    @Override
    public int createSaleList(ShopListDTO shopListDTO) {
        SaleList saleList = new SaleList();
        QueryWrapper<Shop> shopQueryWrapper = new QueryWrapper<>();
        shopQueryWrapper.eq("shop_name", shopListDTO.getShopName());
        Shop shop = shopMapper.selectOne(shopQueryWrapper);
        QueryWrapper<UserDO> userDOQueryWrapper = new QueryWrapper<>();
        userDOQueryWrapper.eq("username", shopListDTO.getUsername());
        UserDO userDO = userMapper.selectOne(userDOQueryWrapper);
        saleList.setShopId(shop.getShopId());
        saleList.setUserId(userDO.getId());
        int insert = saleListMapper.insert(saleList);
        List<ShopListDetailDTO> shopListDetail = shopListDTO.getShopListDetails();
        for (ShopListDetailDTO shopListDetailDTO : shopListDetail) {
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("goods_name", shopListDetailDTO.getGoodsName());
            Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
            SaleDetail saleDetail = new SaleDetail();
            saleDetail.setQuantity(shopListDetailDTO.getNumber());
            saleDetail.setSaleId(saleList.getSaleId());
            saleDetail.setGoodsId(goods.getGoodsId());
            int insert1 = saleDetailMapper.insert(saleDetail);
            ShopStock shopStock = shopStockMapper.selectById(shopListDetailDTO.getShopStockId());
            shopStock.setStockValue(shopListDetailDTO.getStockValue()- shopListDetailDTO.getNumber());
            int update = shopStockMapper.update(shopStock, null);
        }

        return insert;
    }
}
